package org.example.controller.user;

import jakarta.annotation.Resource;
import org.example.domain.Result;
import org.example.domain.user.LoginDTO;
import org.example.domain.user.Users;
import org.example.mapper.UsersMapper;
import org.example.utils.JwtUtil;
import org.example.utils.ThreadLocalUtil;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: 用户
 * @Author: whopxx
 * @CreateTime: 2025-01-04
 */
@RestController
@RequestMapping
public class UserController {
    @Resource
    private UsersMapper usersMapper;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {
        Users user = usersMapper.findByUsername(loginDTO.getUsername());
        if (user == null){
            return Result.error("用户不存在");
        }
        if (!user.getPassword().equals(loginDTO.getPassword())){
            return Result.error("密码错误");
        }

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("username", user.getUsername());
        claims.put("permission", user.getPermission());
        String token = JwtUtil.genToken(claims);

        return Result.success(token);
    }


    @PostMapping("/register")
    public Result register(@RequestBody LoginDTO loginDTO) {
        Users user = usersMapper.findByUsername(loginDTO.getUsername());
        if (user != null){
            return Result.error("用户名已被占用");
        }
        usersMapper.register(loginDTO);
        return Result.success();
    }


    @GetMapping("/userInfo")
    public Result userInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        Users user = usersMapper.findByUsername(username);
        return Result.success(user);
    }

    @PutMapping("/user/update")
    public Result update(@RequestBody Users users) {
        users.setUpdateTime(null);
        usersMapper.updateById(users);
        return Result.success();
    }

    @PostMapping("/user/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> map) {
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");
        String confirmPassword = map.get("confirmPassword");
        if (!newPassword.equals(confirmPassword)){
            return Result.error("两次密码不一致");
        }
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        Users user = usersMapper.findByUsername(username);
        if (!user.getPassword().equals(oldPassword)){
            return Result.error("旧密码错误");
        }
        user.setPassword(newPassword);
        usersMapper.updateById(user);
        return Result.success();
    }


}
